package com.se.db;

import com.se.common.AIUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static com.se.common.Constant.GET_SQL_CONNECTION_FAILED;

public class DbAIUser {
    private static volatile DbAIUser instance;
    private static final Logger logger = LoggerFactory.getLogger(DbAIUser.class);

    private DbAIUser(){
    }

    public static DbAIUser getInstance() {
        if(instance == null) {
            synchronized (DbAIUser.class) {
                if ((instance == null)) {
                    instance = new DbAIUser();
                }
            }
        }

        return instance;
    }

    public void add(AIUser aiUser) throws SQLException{
        String sql = "INSERT INTO ai_user(api_url,model,api_key,ai_name,ai_id,primary_prompt,temperature) " +
                "VALUES(?,?,?,?,?,?,?)";
        Connection conn = DbUtils.getConnection();

        if(conn == null) {
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }

        try(PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, aiUser.getAPI_URL());
            ps.setString(2, aiUser.getModel());
            ps.setString(3, aiUser.getApi_key());
            ps.setString(4, aiUser.getAI_name());
            ps.setString(5, aiUser.getAI_ID());
            ps.setString(6, aiUser.getPrimaryPrompt());
            ps.setDouble(7, aiUser.getTemperature());
            ps.executeUpdate();
        }

        DbUtils.close(conn);
    }

    public AIUser get(String AI_ID) throws SQLException{
        String sql = "SELECT api_url,model,api_key,ai_name,ai_id,primary_prompt,temperature " +
                "FROM ai_user WHERE ai_id=?";
        Connection conn = DbUtils.getConnection();

        if(conn == null) {
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }

        AIUser re = null;

        try(PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, AI_ID);
            try(ResultSet rs = ps.executeQuery()) {
                if(rs.next()) {
                    re = mapAIUser(rs);
                }
            }
        }

        DbUtils.close(conn);
        return re;
    }

    public AIUser mapAIUser(ResultSet rs) throws SQLException{
        AIUser aiUser = new AIUser();
        aiUser.setAI_ID(rs.getString("ai_id"));
        aiUser.setModel(rs.getString("model"));
        aiUser.setAPI_URL(rs.getString("api_url"));
        aiUser.setAI_name(rs.getString("ai_name"));
        aiUser.setPrimaryPrompt(rs.getString("primary_prompt"));
        aiUser.setTemperature(rs.getDouble("temperature"));
        aiUser.setApi_key(rs.getString("api_key"));
        return aiUser;
    }
}
